package com.shixj.demo.Semaphore;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Semaphore;

/**
 * Created by shixj on 2017/9/25.
 */
public class BoundedHashSet <T> {
    private final Set<T> set;
    private final Semaphore semaphore;

    public BoundedHashSet(int bound) {
        this.set = Collections.synchronizedSet(new HashSet<T>());
        this.semaphore = new Semaphore(bound, true);
    }

    public void add(T o) throws InterruptedException {
        semaphore.acquire();//信号量控制可访问的线程数目
        set.add(o);
        System.out.printf("add:%s%n",o);
    }

    public void remove(T o) {
        if (set.remove(o)){
            semaphore.release();//释放掉信号量
            System.out.printf("remove:%s%n",o);
        }
    }
}
